package office

import (
	"io"

	"github.com/extrame/xls"
	"github.com/sirupsen/logrus"
	"github.com/xuri/excelize/v2"
)

// CreateSingleSheetExcel 创建单个sheet的xlsx
// @w 输出
// @sheetName
// @data 数据 格式: {"B1": "语文","C1": "数学"}
func CreateSingleSheetExcel(w io.Writer, sheetName string, data map[string]string) error {
	//创建excel文件
	excel := excelize.NewFile()
	//设置单元格样式
	style, err := excel.NewStyle(`{
    "font":
		{
			"bold": true,
			"color": "#000000"
		}
	}`)
	if err != nil {
		return err
	}
	//创建新表单
	index := excel.NewSheet(sheetName)
	for k, v := range data {
		//设置样式
		err = excel.SetCellStyle(sheetName, k, k, style)
		if err != nil {
			logrus.Error("CrateSingleSheetXlsx设置单元格样式错误", err)
			panic(err)
		}
		//设置单元格的值
		err = excel.SetCellValue(sheetName, k, v)
		if err != nil {
			logrus.Error("CrateSingleSheetXlsx设置单元格值错误", err)
			panic(err)
		}
	}
	//设置默认打开的表单
	excel.SetActiveSheet(index)
	//保存文件到指定路径
	//err := xlsx.SaveAs(filePath)
	err = excel.Write(w)
	if err != nil {
		return err
	}
	return nil
}

// ReadExcel 读取excel
// @return map sheet名: 二维数组
func ReadXlsx(r io.Reader) (map[string][][]string, error) {
	f, err := excelize.OpenReader(r)
	if err != nil {
		return nil, err
	}
	sheets := f.GetSheetList()
	data := make(map[string][][]string)
	for _, sheet := range sheets {
		rows, err := f.GetRows(sheet)
		if err != nil {
			return nil, err
		}
		data[sheet] = rows

	}
	return data, nil

}

/**
 * @Author: DengLibin
 * @Date: Create in 2023-01-06 11:05:29
 * @Description: 读取xls
 */
func ReadXls(filePath string, charset string) (map[string][][]string, error) {

	xlFile, err := xls.Open(filePath, charset)
	if err != nil {
		return nil, err
	}

	var data map[string][][]string = make(map[string][][]string)

	for i := 0; i < xlFile.NumSheets(); i++ {
		if sheet := xlFile.GetSheet(i); sheet != nil {
			sheetName := sheet.Name
			rowSlice := make([][]string, sheet.MaxRow)
			for j := 0; j < int(sheet.MaxRow); j++ {
				row := sheet.Row(j)
				colSlice := make([]string, row.LastCol())
				for index := row.FirstCol(); index < row.LastCol(); index++ {
					colSlice[index] = row.Col(index)
				}
				rowSlice[j] = colSlice
			}
			data[sheetName] = rowSlice

		}
	}

	return data, nil
}
